"""
基础示例包含：打印、变量与类型、函数、类、列表/字典推导、生成器、文件读写、异常处理、上下文管理等。
每个示例都很小，便于学习和修改。

basic_print_and_types：演示打印、变量以及基本类型输出。
functions_demo：带类型注解和返回值的简单函数示例。
comprehensions_demo：列表推导和字典推导示例（筛选/映射）。
Person / class_demo：定义类、方法、repr 和状态修改（生日+1）。
generator_demo / generator_usage：生成器函数与按需迭代示例。
simple_context（@contextmanager）：自定义上下文管理器示例，演示进入/退出语句。
file_read_write_demo：在脚本目录下写入并读取 example.txt（演示文件 I/O）。
exceptions_demo：捕获并处理 ZeroDivisionError 的示例。
iter_zip_enumerate_demo：演示 enumerate 与 zip 的常见用法。
"""

from contextlib import contextmanager
from typing import Iterator
import os


def basic_print_and_types():
	print('\n--- basic_print_and_types ---')
	# 基本打印与类型
	name = 'Alice'
	age = 30
	pi = 3.14159
	print(f'Name: {name}, Age: {age}, Pi approx: {pi}')
	print('Types:', type(name), type(age), type(pi))


def functions_demo(x: int, y: int) -> int:
	"""简单函数示例：带注释和返回值"""
	return x + y


def comprehensions_demo():
	print('\n--- comprehensions_demo ---')
	nums = list(range(10))
	squares = [n * n for n in nums if n % 2 == 0]
	print('squares of even numbers 0-9:', squares)
	# 字典推导
	square_map = {n: n * n for n in range(6)}
	print('square_map:', square_map)


class Person:
	def __init__(self, name: str, age: int):
		self.name = name
		self.age = age

	def birthday(self):
		self.age += 1

	def __repr__(self):
		return f'Person(name={self.name!r}, age={self.age})'


def class_demo():
	print('\n--- class_demo ---')
	p = Person('Bob', 25)
	print('before birthday:', p)
	p.birthday()
	print('after birthday :', p)


def generator_demo() -> Iterator[int]:
	# 生成器：按需生成值
	for i in range(5):
		yield i * 10


def generator_usage():
	print('\n--- generator_usage ---')
	for v in generator_demo():
		print('generated:', v)


@contextmanager
def simple_context(name: str):
	print(f"Entering context: {name}")
	try:
		yield
	finally:
		print(f"Exiting context: {name}")


def file_read_write_demo():
	print('\n--- file_read_write_demo ---')
	filename = os.path.join(os.path.dirname(__file__), 'example.txt')
	# 写入
	with open(filename, 'w', encoding='utf-8') as f:
		f.write('这是写入的示例文本。\n第二行。')
	print('Wrote to', filename)
	# 读取
	with open(filename, 'r', encoding='utf-8') as f:
		content = f.read()
	print('Read content:\n', content)


def exceptions_demo():
	print('\n--- exceptions_demo ---')
	try:
		x = 1 / 0
	except ZeroDivisionError as e:
		print('Caught an exception:', type(e).__name__, '-', e)


def iter_zip_enumerate_demo():
	print('\n--- iter_zip_enumerate_demo ---')
	a = ['x', 'y', 'z']
	b = [1, 2, 3]
	for idx, (ch, num) in enumerate(zip(a, b), start=1):
		print(idx, ch, num)


def main():
	basic_print_and_types()
	print('\n--- functions_demo ---')
	print('2 + 3 =', functions_demo(2, 3))
	comprehensions_demo()
	class_demo()
	generator_usage()
	with simple_context('my-block'):
		print('Inside the context block')
	file_read_write_demo()
	exceptions_demo()
	iter_zip_enumerate_demo()


if __name__ == '__main__':
	main()


